<!-- 抄表记录管理页面 -->
<template>
  <div class="meter-reading">
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="业主ID">
          <el-select v-model="searchForm.ownerId" placeholder="请选择业主">
            <el-option v-for="owner in owners" :key="owner.id" :label="owner.realName || owner.username || owner.id" :value="owner.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="表类型">
          <el-select v-model="searchForm.meterType" placeholder="请选择表类型">
            <el-option label="水表" value="水表"></el-option>
            <el-option label="电表" value="电表"></el-option>
            <el-option label="气表" value="气表"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="loadAllData">查询全部</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
        <el-table-column prop="roomId" label="楼栋ID" width="120">
          <template #default="scope">
            {{ ownerInfoMap[scope.row.ownerId]?.buildingId || '未知' }}
          </template>
        </el-table-column>
        <!-- 修改业主ID列为业主姓名 -->
        <el-table-column prop="ownerId" label="业主" width="120">
          <template #default="scope">
            {{ ownerNameMap[scope.row.ownerId] || scope.row.ownerId }}
          </template>
        </el-table-column>
        <el-table-column prop="meterType" label="表类型" width="100"></el-table-column>
        <el-table-column prop="meterNumber" label="表号" width="120"></el-table-column>
        <el-table-column prop="lastRead" label="上次读数"></el-table-column>
        <el-table-column prop="currentRead" label="本次读数"></el-table-column>
        <el-table-column prop="readDate" label="抄表日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.readDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="reader" label="抄表员" width="120"></el-table-column>
        <el-table-column prop="price" label="单价(元)"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { getOwnerById } from '../api/owner'

export default {
  name: 'MeterReading',
  setup() {
    // 搜索表单数据
    const searchForm = reactive({
      roomId: '',
      ownerId: '',
      meterType: ''
    })

    // 表格数据
    const tableData = ref([])
    // 业主姓名映射
    const ownerNameMap = ref({})
    // 业主信息映射
    const ownerInfoMap = ref({})
    // 业主列表
    const owners = ref([])

    // 批量获取业主姓名
    const fetchOwnerNames = async (ownerIds) => {
      const uniqueIds = [...new Set(ownerIds.filter(Boolean))]
      for (const id of uniqueIds) {
        if (!ownerNameMap.value[id]) {
          try {
            const res = await getOwnerById(Number(id))
            ownerNameMap.value[id] = res.data?.realName || '未知'
          } catch (error) {
            ownerNameMap.value[id] = '未知'
          }
        }
      }
    }

    // 批量获取业主信息
    const fetchOwnerInfos = async (ownerIds) => {
      const uniqueIds = [...new Set(ownerIds.filter(Boolean))]
      for (const id of uniqueIds) {
        if (!ownerInfoMap.value[id]) {
          try {
            const res = await getOwnerById(Number(id))
            ownerInfoMap.value[id] = res.data || {}
          } catch {
            ownerInfoMap.value[id] = {}
          }
        }
      }
    }

    // 获取业主列表
    const fetchOwners = async () => {
      try {
        const res = await request.get('/owner-server/queryOwner')
        owners.value = res.data
      } catch (e) {
        ElMessage.error('获取业主列表失败')
      }
    }

    // 加载所有数据
    const loadAllData = async () => {
      try {
        const response = await request.get('/infrastructure-server/meter-reading/all')
        tableData.value = response.data
        // 同时获取业主姓名和业主信息
        await Promise.all([
          fetchOwnerNames(response.data.map(item => item.ownerId)),
          fetchOwnerInfos(response.data.map(item => item.ownerId))
        ])
      } catch (error) {
        ElMessage.error('获取数据失败')
        console.error('Error:', error)
      }
    }

    // 条件查询
    const handleSearch = async () => {
      try {
        // 构建查询参数，移除空值
        const params = {}
        Object.keys(searchForm).forEach(key => {
          if (searchForm[key]) {
            params[key] = searchForm[key]
          }
        })

        const response = await request.post('/infrastructure-server/meter-reading/query', params)
        tableData.value = response.data
        // 同时获取业主姓名和业主信息
        await Promise.all([
          fetchOwnerNames(response.data.map(item => item.ownerId)),
          fetchOwnerInfos(response.data.map(item => item.ownerId))
        ])
      } catch (error) {
        ElMessage.error('查询失败')
        console.error('Error:', error)
      }
    }

    // 重置表单
    const handleReset = () => {
      searchForm.roomId = ''
      searchForm.ownerId = ''
      searchForm.meterType = ''
      loadAllData()
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleString()
    }



    // 初始加载
    loadAllData()
    fetchOwners()

    return {
      searchForm,
      tableData,
      handleSearch,
      handleReset,
      loadAllData,
      formatDate,
      ownerNameMap,
      ownerInfoMap,
      owners,
    }
  }
}
</script>

<style scoped>
.meter-reading {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
</style> 